import { FC, forwardRef, useImperativeHandle, useRef } from "react";
import { useSelector } from "react-redux";
import { stateType } from "@/store";
import { MessageType, infoType } from "@/store/MessageStore";
import TextMessage from "../MessageComponents/TextMessage";
import ImageMessage from "../MessageComponents/ImageMessage";
import MsgBasicInfo from "../MsgBasicInfo";
import PrologueMessage from "../MessageComponents/PrologueMessage";
import ButtonsMessage from "../MessageComponents/ButtonsMessage";
import AIMessage from "../MessageComponents/AIMessage";
import TipsMEssage from "../MessageComponents/TipsMessage";
import { TransitionGroup, CSSTransition } from 'react-transition-group'
import 'animate.css';
import './index.css'

const ChartBox: FC = forwardRef((_, ref: any) => {
    const messageList = useSelector<stateType>((state) => state.MessageReducer) as MessageType[]
    const { chatid } = useSelector((state: stateType) => state.CustomerInfoReducer)
    const MsgRef = useRef({})
    const returnRightCom = (type: string, info: infoType, position: any, isdelete: any = null, id: string = '') => {
        
        if (type === 'text') {
            return <TextMessage {...info} position={position} />
        } else if (type === 'image') {
            return <ImageMessage {...info} position={position} />
        } else if (type === 'Prologue') {
            return <PrologueMessage {...info} position={position} />
        } else if (type === 'AI') {
            return <AIMessage {...info} position={position} isdelete={isdelete} id={id} />
        } else if (type === 'buttons') {
            return <ButtonsMessage {...info} position={position} />
        } else if (type === 'tips') {
            return <TipsMEssage {...info} />
        }
    }

    const ReturnLastMsgNode = (id: string) => {
        return MsgRef[id]
    }

    useImperativeHandle(ref, () => {
        return {
            ReturnLastMsgNode
        }
    })

    return <>
        <TransitionGroup className="message-list">
            {messageList.map((item, index) => {
                const { info, sendid, isdelete = 'null', id } = item;
                const position = (sendid === chatid ? 'right' : 'left')
                return (
                    <CSSTransition key={item.id} timeout={500} classNames={position == 'right' ? 'message-item' : 'messageCus-item'}>
                        <div ref={(el) => MsgRef[id] = el}>
                            <MsgBasicInfo {...item} position={position} >
                                {returnRightCom(info.type, info, position, isdelete, id)}
                            </MsgBasicInfo>
                        </div>
                    </CSSTransition>
                );
            })}
        </TransitionGroup>
    </>
})



export default ChartBox